<template>
  <div>
    <Card>
      <Button type="primary" @click="showAddModal" class="mr10">添加日记</Button>
      <Button
        type="primary"
        :loading="refreshLoading"
        @click="refreshEvent"
        shape="circle"
        icon="md-refresh"
        class="fr"
      ></Button>
      <Select v-model="searchTypeValue"  class="searchInputClass">
        <Option v-for="item in searchType" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>
      <Input
        v-model="searchKeyWord"
        placeholder="请输入搜索关键字"
        :type="searchInputType"
        suffix="ios-search"
       class="searchKeyWordInputClass"
      />
    </Card>

    <Card>
      <Tables
        ref="tables"
        editable
        v-model="searchData"
        :columns="columns"
        :loading="loading"
        :border="true"
        size="large"
      />
    </Card>
    <Page
      :total="num"
      @on-change="changePage"
      show-sizer
      show-elevator
      show-total
      :page-size="pageSize"
      :page-size-opts="$store.state.pageSizeArray"
      @on-page-size-change="changePageSize"
      style="margin-top: 12px; float: right"
    />
    <Modal
      title="添加日记"
      v-model="addModal"
      fullscreen
      @on-ok="addDataEvent"
      :mask-closable="false"
      width="90%"
    >
      <Form :model="addData" :label-width="80" :rules="ruleValidate">
        <FormItem label="日期：" prop="date">
          <Input v-model="addData.date" type="date" placeholder="请选择日期." class="inputWidth200"></Input>
        </FormItem>
        <FormItem label="星期：" prop="week">
          <Select v-model="addData.week" class="inputWidth200">
            <Option value="1">星期一</Option>
            <Option value="2">星期二</Option>
            <Option value="3">星期三</Option>
            <Option value="4">星期四</Option>
            <Option value="5">星期五</Option>
            <Option value="6">星期六</Option>
            <Option value="0">星期日</Option>
          </Select>
        </FormItem>
        <FormItem label="天气：" prop="weather">
          <Input
            v-model="addData.weather"
            maxlength="6"
            type="text"
            placeholder="请输入天气，字数不超过6字."
            class="inputWidth200"
          ></Input>
        </FormItem>
        <FormItem label="内容：" prop="notepad">
          <Input
            v-model="addData.notepad"
            maxlength="1000"
            show-word-limit
            type="textarea"
            placeholder="请输入内容，字数在1-1000位之间."
            :rows="20"
          ></Input>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      title="修改日记"
      v-model="editModal"
      fullscreen
      :mask-closable="false"
      @on-ok="editDataEventOk"
      @on-cancel="editDataEventCancel"
    >
      <Form :model="editData" :label-width="80" :rules="ruleValidate">
        <FormItem label="日期：" prop="date">
          <Input v-model="editData.date" type="date" placeholder="请选择日期。" class="inputWidth200"></Input>
        </FormItem>
        <FormItem label="星期：" prop="week">
          <Select v-model="editData.week" class="inputWidth200">
            <Option value="1">星期一</Option>
            <Option value="2">星期二</Option>
            <Option value="3">星期三</Option>
            <Option value="4">星期四</Option>
            <Option value="5">星期五</Option>
            <Option value="6">星期六</Option>
            <Option value="0">星期日</Option>
          </Select>
        </FormItem>
        <FormItem label="天气：" prop="weather">
          <Input v-model="editData.weather" maxlength="6" type="text" placeholder="请输入天气，字数不超过6字。" class="inputWidth200"></Input>
        </FormItem>
        <FormItem label="内容：" prop="notepad">
          <Input
            v-model="editData.notepad"
            maxlength="1000"
            show-word-limit
            type="textarea"
            placeholder="请输入内容，字数在1-1000位之间."
            :rows="20"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import expandRow from "_c/tables/config-expand.vue";
import {
  getLuggagesData,
  addLuggageData,
  deleteLuggageData,
  finishData,
  editLuggageData
} from "@/api/content/luggage/notepad";
export default {
  name: "tables_page",
  components: {
    Tables,
    expandRow
  },
  data() {
    return {
      refreshLoading: false,
      addData: { weather: "晴" },
      addModal: false,
      editData: {},
      editModal: false,
      num: 0,
      columns: [
        {
          title: "日期",
          key: "date",
          width: 150,
          align: "center",
          sortable: true
        },
        { title: "星期", key: "week", width: 100, align: "center" },
        { title: "天气", key: "weather", width: 140, align: "center" },
        {
          title: "更多",
          type: "expand",
          width: 100,
          align: "center",
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row
              }
            });
          }
        },
        { title: "内容", key: "notepad", ellipsis: true, align: "center" },

        {
          title: "操作",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.editData = params.row;
                      this.showEditModal();
                    }
                  }
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    type: "error",
                    size: "large",
                    title: "你确定要删除吗?"
                  },

                  on: {
                    "on-ok": () => {
                      this.deleteDataEvent(params.row);
                    },
                    "on-cancel": () => {
                      this.$Message.info("您取消了删除.");
                    }
                  }
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "warning"
                      },
                      style: {
                        marginRight: "5px"
                      }
                    },
                    "删除"
                  )
                ]
              )
            ]);
          }
        }
      ],
      //搜索类型
      searchType: [
        {
          label: "日期",
          value: "date"
        },
        {
          label: "星期",
          value: "week"
        },
        {
          label: "天气",
          value: "weather"
        },
        {
          label: "内容",
          value: "notepad"
        }
      ],
      //搜索类型值
      searchTypeValue: "date",
      //搜索关键字
      searchKeyWord: "",
      tableData: [],
      num: 0,
      pageCurrent: 1,
      pageSize: 10,
      loading: true,
      ruleValidate: {
        date: [
          {
            required: true,
            message: "您未选择日期或格式不正确，请重新选择.",
            trigger: "blur"
          }
        ],
        week: [
          {
            required: true,
            message: "您未选择星期或格式不正确，请重新选择.",
            trigger: "blur"
          }
        ],
        weather: [
          {
            required: true,
            message: "您输入的天气不能为空，字数在1-6位之间，请重新输入.",
            trigger: "blur"
          }
        ],
        notepad: [
          {
            required: true,
            message: "您输入的内容格式错误，字数在1-1000位之间，请重新输入.",
            trigger: "blur"
          }
        ]
      },
      searchInputType: "date"
    };
  },
  computed: {
    searchData() {
      if (!this.searchKeyWord) {
        return this.tableData;
      }
      return this.tableData.filter(item => {
        return item[this.searchTypeValue].indexOf(this.searchKeyWord) !== -1;
      });
    }
  },
  methods: {
    //添加日记
    addDataEvent() {
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        addLuggageData(this.addData).then(res => {
          if (res.data.code == 0) {
            this.getData(this.pageCurrent, this.pageSize);
            this.$Message.success("您成功添加了一篇日记.");
            this.addData.notepad = "";
          } else if (res.data.code == 1010) {
            this.$router.push("/login");
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
          } else {
            this.$Message.error("您添加日记失败了，错误原因：" + res.data.msg);
          }
        });
      }
    },
    editDataEventOk() {
      if (!this.requireFormData(this.editData)) {
        this.getData(this.pageCurrent, this.pageSize);
        return;
      } else {
        editLuggageData(this.editData)
          .then(res => {
            if (res.data.code == 0) {
              this.getData(this.pageCurrent, this.pageSize);
              this.$Message.success("您成功修改了一篇日记.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您修改日记失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch(err => {
            this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },
    editDataEventCancel() {
      this.getData(this.pageCurrent, this.pageSize);
    },
    requireFormData(data) {
      if (data.week < 0 || data.week > 6) {
        this.$Message.warning("您未选择星期，请选择.");
        return false;
      } else if (!data.date || data.date.length !== 10) {
        this.$Message.warning("您选择的日期格式错误，请重新选择.");
        return false;
      } else if (!data.weather || data.weather.length > 6) {
        this.$Message.warning(
          "您输入的天气格式错误，字数在1-6位之间，请重新输入."
        );
        return false;
      } else if (!data.notepad || data.weather.length > 1000) {
        this.$Message.warning(
          "您输入的内容格式错误，字数在1-1000位之间，请重新输入."
        );
        return false;
      } else {
        return true;
      }
    },
    //删除日记
    deleteDataEvent(row) {
      deleteLuggageData(row.id)
        .then(res => {
          if (res.data.code == 0) {
            this.tableData.splice(row["_index"], 1);
            this.$Message.success("您成功删除了一篇日记.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您删除数据失败了，错误原因：" + res.data.msg);
          }
        })
        .catch(err => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //打开添加页面
    showAddModal() {
      this.addModal = true;
    },

    //打开修改页面
    showEditModal() {
      this.editModal = true;
      this.editData.week = this.weekToInt(this.editData.week);
    },
    refreshEvent() {
      this.refreshLoading = true;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //获取表格日记
    getData(page, pageSize) {
      this.loading = true;
      getLuggagesData(page, pageSize)
        .then(res => {
          if (res.data.code == 0) {
            this.num = res.data.num;
            this.tableData = res.data.data;
            let arrLength = this.tableData.length;
            for (let i = 0; i < arrLength; i++) {
              this.tableData[i].week = this.weekToString(
                parseInt(this.tableData[i].week)
              );
            }
            this.refreshLoading = false;
            this.loading = false;
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "自动获取数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch(err => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },
    formatDate() {
      let nowDate = new Date();
      let y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = nowDate.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + m + "-" + d;
    },
    getWeek() {
      return new Date().getDay().toString();
    },
    weekToString(value) {
      let arr = Array(
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六"
      );
      return arr[value];
    },
    weekToInt(value) {
      let week = value.charAt(2);
      let weekday = "0";
      switch (week) {
        case "一":
          weekday = "1";
          break;
        case "二":
          weekday = "2";
          break;
        case "三":
          weekday = "3";
          break;
        case "四":
          weekday = "4";
          break;
        case "五":
          weekday = "5";
          break;
        case "六":
          weekday = "6";
          break;
        default:
          weekday = "0";
          break;
      }
      return weekday;
    },

    //第几页日记
    changePage(index) {
      this.pageCurrent = index;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //每页显示日记
    changePageSize(size) {
      this.pageSize = size;
      this.getData(this.pageCurrent, this.pageSize);
    }
  },
  created() {
    this.pageSize = this.$store.state.pageSize;
    this.getData(this.pageCurrent, this.pageSize);
    this.addData.date = this.formatDate();
    this.addData.week = this.getWeek();
  },
  watch: {
    searchTypeValue(value) {
      this.searchInputType = value == "date" ? "date" : "text";
    }
  }
};
</script>
